import React, { useState, useEffect } from "react";
import { Table, Button, Card, Divider, Pagination, Modal, message, Popconfirm } from "antd";
import {
  categoryAdd,
  categoryUpdate,
  categoryDel,
  categoryPage
} from "@/api/category";
import AddForm from "./addForm";

function Category() {
  const [categories, setCategories] = useState([])
  const [loading, setLoading] = useState(false)
  const [total, setTotal] = useState(0)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [cateName, setCateName] = useState('')
  const [typeid, setTypeid] = useState('')

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name"
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      responsive: ["md"]
    },
    {
      title: "操作",
      dataIndex: "Operation",
      key: "Operation",
      responsive: ["lg"],
      render: (value, row, index) => {
        return (
          <div>
            <Button
              type='primary'
              size='small'
              onClick={() => addFrom(row)}
            >
              修改
            </Button>
            <Divider type='vertical' />
            <Popconfirm
              title="您确定要删除此项吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => delBtn(row.typeid)}
            >
              <Button
                type='primary'
                size='small'
                danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      }
    }
  ];

  const getCategoriesList = () => {
    setLoading(true)
    categoryPage({ pageNo, pageSize })
      .then(res => {
        setCategories(res.data.data)
        setTotal(res.data.total)
        setLoading(false)
      })
      .catch(err => {
        setLoading(false)
      });
  };

  const paginationChange = (pageNo, pageSize) => {
    setPageNo(pageNo)
    setPageSize(pageSize)

    getCategoriesList()
  };

  const addFrom = row => {
    if (row) {
      // 编辑
      setTypeid(row.typeid)
      setCateName(row.name)
      setIsModalVisible(true)
    } else {
      // 新增
      setTypeid('')
      setCateName('')
      setIsModalVisible(true)
    }
  };

  const handleCancel = () => {
    setTypeid('')
    setCateName('')
    setIsModalVisible(false)
  };

  useEffect(() => {
    getCategoriesList();
  }, [])// eslint-disable-line react-hooks/exhaustive-deps

  const onOk = val => {
    if (typeid) {
      categoryUpdate({ typeid: typeid, name: val.name }).then(res => {
        if (res.data.code === 200) {
          getCategoriesList();
          message.success("修改成功");
        } else {
          message.error(res.data.msg);
        }
      });
    } else {
      categoryAdd({ name: val.name }).then(res => {
        if (res.data.code === 200) {
          getCategoriesList();
          message.success("添加成功");
        } else {
          message.error(res.data.msg);
        }
      });
    }
    handleCancel()
  };

  const delBtn = typeid => {
    categoryDel({ typeid })
      .then(res => {
        if (res.data.code === 200) {
          getCategoriesList()
          return message.success("删除成功")
        }
        message.error(res.data.msg)
      })
  }

  const title = "商品分类列表";
  const extra = <Button onClick={addFrom}>添加</Button>;

  return (
    <Card title={title} extra={extra}>
      <Table
        rowKey='typeid'
        loading={loading}
        columns={columns}
        dataSource={categories}
        pagination={false}
      />
      <br />
      {total ? (
        <Pagination
          total={total}
          showSizeChanger
          showQuickJumper
          showTotal={total => `共 ${total} 条`}
          onChange={paginationChange}
        />
      ) : (
        ""
      )}
      <Modal
        title='添加商品分类'
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <AddForm
          onOk={onOk}
          onCancel={handleCancel}
          name={cateName}
        />
      </Modal>
    </Card>
  );
}

export default Category;